<!-- 家庭成员 -->
<template>
  <publicPage isNavbar>
    <view slot="navbar">
      <u-navbar :placeholder="true" autoBack>
        <view slot="center">
          <view class="fz-14 tc">{{ info.id ? "编辑成员" : "添加成员" }}</view>
        </view>
      </u-navbar>
    </view>

    <scroll-view
      scroll-y
      class="familyDetails"
      :style="
        info.id
          ? 'height: calc(100% - 220rpx - 118rpx);'
          : 'height: calc(100% - 220rpx);'
      "
    >
      <view class="bgf">
        <view class="mx-15 borderB disFlxJS linh-50">
          <view class="shrink0 pr-50">
            <view>姓名</view>
          </view>
          <view class="disFlxAC">
            <u--input
              v-model="info.username"
              placeholder="请输入姓名"
              border="none"
              inputAlign="right"
              :maxLength="10"
            ></u--input>
          </view>
        </view>
        <view class="mx-15 borderB disFlxJS linh-50">
          <view class="shrink0 pr-50">
            <view>性别</view>
          </view>
          <view class="disFlxAC" @click="sexChangeShow = true">
            <text class="pl-50 pr-10" v-if="info.sex || info.sex === 0">{{
              info.sex == "0" ? "男" : "女"
            }}</text>
            <text v-else style="color: #c8c9cc"> 请选择性别 </text>
            <u-icon name="arrow-right" color="#AAABAB" />
          </view>
        </view>
        <view class="mx-15 borderB disFlxJS linh-50">
          <view class="shrink0 pr-50">
            <view>手机号</view>
          </view>
          <view class="disFlxAC">
            <u--input
              type="number"
              v-model="info.userphone"
              placeholder="请输入手机号"
              border="none"
              inputAlign="right"
              :maxLength="11"
            ></u--input>
          </view>
        </view>
        
        <view class="mx-15 borderB disFlxJS linh-50">
          <view class="shrink0 pr-50">
            <view>身份证号</view>
          </view>
          <view class="disFlxAC">
            <u--input
              v-model="info.idcardno"
              placeholder="请输入身份证号"
              border="none"
              inputAlign="right"
              :maxLength="18"
              @change="idcardChange"
            ></u--input>
          </view>
        </view>
        <!-- 通过身份证计算年龄 -->
        <view class="mx-15 borderB disFlxJS linh-50">
          <view class="shrink0 pr-50">
            <view>出生日期</view>
          </view>
          <view class="disFlxAC" @click="birthdayChangeShow = true">
            <text class="pl-50 pr-10" v-if="info.birthday">{{ info.birthday }}</text>
            <text v-else style="color: #c8c9cc"> 请选择出生日期 </text>
            <u-icon name="arrow-right" color="#AAABAB" />
          </view>
        </view>
        <view class="mx-15 disFlxJS linh-50">
          <view class="shrink0 pr-50">
            <view>关系</view>
          </view>
          <view class="disFlxAC" @click="sexRelationshipShow = true">
            <text class="pl-50 pr-10" v-if="info.relationship">{{ shipList.find(v=> v.value == info.relationship).label }}</text>
            <text v-else style="color: #c8c9cc"> 请选择关系 </text>
            <u-icon name="arrow-right" color="#AAABAB" />
          </view>
        </view>
      </view>
    </scroll-view>

    <view class="px-15 py-15 fexdBtn">
      <u-button
        type="primary"
        text="保存"
        :customStyle="{
          fontSize: '32rpx',
          borderRadius: '20rpx',
          height: '88rpx',
        }"
        :throttleTime="500"
        @click="configEdit"
      ></u-button>
      <u-button
        v-if="info.id"
        type="error"
        text="删除"
        :customStyle="{
          marginTop: '30rpx',
          fontSize: '32rpx',
          borderRadius: '20rpx',
          height: '88rpx',
        }"
        :throttleTime="500"
        @click="deleteUser"
      ></u-button>
    </view>

    <u-popup
      :show="sexChangeShow"
      :round="10"
      closeOnClickOverlay
      @close="sexChangeShow = false"
    >
      <view class="fz-17 fw-5">
        <view
          class="linh-50 tc borderBottom"
          :class="{ colorZS: info.sex == '0' }"
          @click="changeSex('0')"
          >男</view
        >
        <view
          class="linh-50 tc borderBottom"
          :class="{ colorZS: info.sex == '1' }"
          @click="changeSex('1')"
          >女</view
        >
        <view style="height: 12rpx; background-color: #f5f5f5"></view>
        <view class="linh-50 tc" @click="sexChangeShow = false">取消</view>
      </view>
    </u-popup>

    <u-popup
      :show="sexRelationshipShow"
      :round="10"
      closeOnClickOverlay
      @close="sexRelationshipShow = false"
    >
      <view class="fz-17 fw-5">
        <view
          v-for="item in shipList"
          :key="item.value"
          class="linh-50 tc borderBottom"
          :class="{ colorZS: info.relationship == item.value}"
          @click="changeRelationship(item.value)"
          >{{item.label}}</view
        >
      </view>
    </u-popup>

    <u-datetime-picker
      :show="birthdayChangeShow"
      :title="datetimeObj.title"
      :maxDate="datetimeObj.maxDate"
      :minDate="datetimeObj.minDate"
      :loading="true"
      v-model="dateTime"
      mode="date"
      @confirm="changeTime"
      @cancel="birthdayChangeShow = false"
    ></u-datetime-picker>
  </publicPage>
</template>

<script>
import userApi from "@/api/user";
const dayjs = require("dayjs");

export default {
  data() {
    return {
      info: {
        username: "",
        userphone: "",
        sex: "", // sex == "0" ? "男" : "女"
        idcardno: "",
        birthday: "",
        relationship: null, // 关系
      },
      shipList: [
        {
          label: "父母",
          value: 1,
        },
        {
          label: "子女",
          value: 2,
        },
        {
          label: "配偶",
          value: 3,
        },
        {
          label: "亲属",
          value: 4,
        },
        {
          label: "朋友",
          value: 5,
        },
        {
          label: "其他",
          value: 6,
        },
      ],
      sexChangeShow: false,
      sexRelationshipShow: false,
      birthdayChangeShow: false,
      datetimeObj: {
        title: "出生日期",
        maxDate: Date.now(), // 当前时间
        minDate: Date.now() - 86400000 * 365 * 100, // 100年前
      },
      dateTime: Date.now() - 86400000 * 365 * 30, // 默认30年前
    };
  },
  onLoad(option) {
    if (option.id) {
      this.info = JSON.parse(JSON.stringify(this.$store.state.sessionObj));
      if(this.info.birthday){
        this.dateTime = dayjs(this.info.birthday).valueOf()
      }
      this.$store.commit("SET_SESSIONOBJ", {});
    }
    console.log(JSON.parse(JSON.stringify(this.info)))
  },
  methods: {
    // 刪除成員
    deleteUser() {
      userApi.deleteFamily({ id: this.info.id }).then((res) => {
        uni.showToast({
          title: "刪除成功",
          icon: "none",
          complete: () => {
            setTimeout(() => {
              this.goBack();
            }, 1500);
          },
        });
      });
    },
    // 选择性别
    changeSex(sex) {
      this.info.sex = sex;
      this.sexChangeShow = false;
    },
    // 选择关系
    changeRelationship(ship){
      this.info.relationship = ship
      this.sexRelationshipShow = false;
    },
    // 身份证输入
    idcardChange(val){ 
      if(val.length === 18){
        const IDCard = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
        if(IDCard.test(val)){
          this.info.birthday = `${val.substring(6,10)}-${val.substring(10,12)}-${val.substring(12,14)}`
        }
      }
    },
    // 切换出生日期
    changeTime() {
      this.birthdayChangeShow = false;
      setTimeout(() => {
        this.info.birthday = dayjs(this.dateTime).format("YYYY-MM-DD");
      }, 1000);
    },
    // 编辑确认
    configEdit() {
      const Phone =  /^0?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$/
      const IDCard = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
      if(!this.info.username){
        uni.showToast({title: '请输入姓名',icon: 'none'})
        return
      }else if(this.info.sex !== 0 && !this.info.sex){
        uni.showToast({title: '请选择性别',icon: 'none'})
        return
      }else if(!this.info.userphone){
        uni.showToast({title: '请输入手机号',icon: 'none'})
        return
      }else if(!Phone.test(this.info.userphone)){
        uni.showToast({title: '手机号错误',icon: 'none'})
        return
      }else if(this.info.idcardno && !IDCard.test(this.info.idcardno)){
        uni.showToast({title: '身份证号错误',icon: 'none'})
        return
      }else if(!this.info.relationship){
        uni.showToast({title: '请选择关系',icon: 'none'})
        return
      }
      if(this.info.id){
        userApi.updateFamily(this.info).then(()=>{
          uni.showToast({
            title: "修改成功",
            complete: () => {
              setTimeout(() => {
                this.goBack();
              }, 1500);
            },
          });
        })
      }else{
        userApi.addFamily(this.info).then(() => {
          uni.showToast({
            title: "添加成功",
            complete: () => {
              setTimeout(() => {
                this.goBack();
              }, 1500);
            },
          });
        });
      }
    },
  },
};
</script>
<style lang='scss' scoped>
.familyDetails {
  padding-top: 30rpx;
  .fexdBtn {
    position: fixed;
    left: 0;
    width: 100%;
    bottom: 0;
    bottom: constant(safe-area-inset-bottom);
    bottom: env(safe-area-inset-bottom);
  }
}
</style>